<script lang="ts" setup>
import { useForm } from '@/hooks/web/useForm'
import { FormSchema } from '@/types/form'
import * as FeedApi from '@/api/official-website/unit/feed'
import { ref, reactive } from 'vue'
import { useI18n } from '@/hooks/web/useI18n'
import { Plus } from '@element-plus/icons-vue'
import type { UploadFile, UploadProps, UploadUserFile, UploadRawFile } from 'element-plus'
import { ElMessage } from 'element-plus'
import { getAccessToken, getTenantId } from '@/utils/auth'
import { object } from 'vue-types'

const message = useMessage()
const { t } = useI18n()

const dialogVisible = ref(false)
const dialogTitle = ref('新增信息流')
const formLoading = ref(false)
const formType = ref<'create' | 'update'>('create')

const testVisible = ref(false)
const videoVisible = ref(true)

// 上传视频
const fileList = ref<UploadUserFile[]>([])
const updateUrl = import.meta.env.VITE_UPLOAD_URL
const uploadHeaders = ref({
  Authorization: 'Bearer ' + getAccessToken(),
  'tenant-id': getTenantId()
})
const recordVideo = ref<string>()

const schema = reactive<FormSchema[]>([
  {
    field: 'feedTitle',
    label: '信息流标题',
    value: '',
    component: 'Input',
    formItemProps: {
      rules: [{ required: true, message: '请输入信息流标题' }]
    }
  },
  {
    field: 'feedType',
    label: '信息流类型',
    value: 1,
    component: 'Select',
    componentProps: {
      options: [
        { label: '图片', value: 1 },
        { label: '视频', value: 2 }
      ],
      onChange: (value: number) => {
        visibleFeedType(value)
      }
    },
    formItemProps: {
      rules: [{ required: true, message: '请选择信息流类型' }]
    }
  },
  {
    field: 'feedShowType',
    label: '信息流摆放',
    component: 'Select',
    value: 1,
    componentProps: {
      options: [
        { label: '对齐', value: 1 },
        { label: '不规则', value: 2 }
      ]
    },
    formItemProps: {
      rules: [{ required: true, message: '请选择信息流摆放' }]
    }
  },
  {
    field: 'imageUrls',
    label: '轮播图',
    value: '',
    component: 'UploadImgs',
    componentProps: {
      limit: '6'
    },
    formItemProps: {
      rules: [{ required: true, message: '请上传图文轮播图' }]
    },
    hidden: testVisible
  },
  {
    field: 'videoUrl',
    label: '上传视频',
    value: '',
    hidden: videoVisible,
    formItemProps: {
      rules: [{ required: true, message: '上传视频' }]
    }
  },
  {
    field: 'videoCoverUrl',
    label: '视频封面',
    value: '',
    component: 'UploadImg',
    formItemProps: {
      rules: [{ required: true, message: '请上传视频封面' }]
    },
    hidden: videoVisible
  },
  {
    field: 'feedContent',
    label: '图文内容',
    component: 'Editor',
    formItemProps: {
      rules: [{ required: true, message: '信息流内容不能为空' }]
    },
    hidden: testVisible
  },
  {
    field: 'feedContent',
    label: '视频介绍',
    component: 'Input',
    formItemProps: {
      rules: [{ required: true, message: '信息流内容不能为空' }]
    },
    componentProps: {
      type: 'textarea',
      autosize: {
        minRows: 2,
        maxRows: 4
      },
      showWordLimit: false,
      resize: 'none'
    },
    hidden: videoVisible
  },
  {
    field: 'sortNo',
    label: '排序',
    value: 0,
    component: 'InputNumber'
  }
])

const { register, elFormRef, methods: formMethods } = useForm()

const open = (type: 'create' | 'update', id?: string) => {
  dialogVisible.value = true
  dialogTitle.value = type === 'update' ? '编辑信息流' : '新增信息流'
  formType.value = type
  // 重置数据
  visibleFeedType(1)
  fileList.value = []
  if (type === 'update') {
    formLoading.value = true
    FeedApi.getFeedById(id!).then((data) => {
      console.log('update: ', data)
      visibleFeedType(data.feedType)

      // 处理视频
      if (data.feedType === 2) {
        fileList.value.push({ name: '视频', url: data.videoUrl })
        recordVideo.value = data.videoUrl
        formMethods.setValues(data)
      } else {
        // 处理图片
        const imageUrls = data.imageUrls.map((item) => {
          return {
            name: '图片',
            url: item
          }
        })
        formMethods.setValues({ ...data, imageUrls })
      }

      formLoading.value = false
    })
  }
}
defineExpose({ open })

// 显示类型
const visibleFeedType = (value?: number) => {
  if (value) {
    testVisible.value = !(value === 1)
    videoVisible.value = !(value === 2)
  }
}

const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 处理视频流校检规则
  const refVideo = (await formMethods.getFormData()) || {}
  if (refVideo.feedType === 2) {
    formMethods.setValues({ ...refVideo, videoUrl: { name: '视频', url: recordVideo.value } })
  }
  // 校验表单
  if (!elFormRef.value) return
  const valid = await elFormRef.value.validate()
  if (!valid) return
  if (recordVideo.value?.length === 0) {
    message.error('请上传视频')
    return
  }
  // 提交请求
  formLoading.value = true

  try {
    const formData = (await formMethods.getFormData()) || {}

    if (formType.value === 'create') {
      console.log('创建信息流：', formData)
      if (formData.feedType === 1) {
        // 获取图片url
        const imgs: string[] = formData.imageUrls.map((item) => {
          return item.response.data
        })
        const data = {
          ...formData,
          imageUrls: imgs,
          videoUrl: '',
          videoCoverUrl: ''
        }
        await FeedApi.createFeed(data)
      } else {
        const videoUrl = recordVideo.value
        const data = {
          ...formData,
          videoUrl: videoUrl,
          imageUrls: []
        }
        await FeedApi.createFeed(data)
      }

      message.success(t('common.createSuccess'))
    } else {
      console.log('更新信息流：', formData)
      if (formData.feedType === 1) {
        // 获取图片url
        const imgs: string[] = formData.imageUrls.map((item) => {
          if (item === object) return item.response.data
          return item.url
        })
        const data = {
          ...formData,
          imageUrls: imgs
        }
        await FeedApi.updateFeed(data)
      } else {
        const videoUrl = recordVideo.value
        const data = {
          ...formData,
          videoUrl
        }
        console.log(data)
        await FeedApi.updateFeed(data)
      }

      message.success(t('common.updateSuccess'))
    }
    fileList.value = []
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

// 视频上传前
const beforeUploadVideo = (file) => {
  const isLitmit = file.size / 1024 / 1024
  // 判断视频格式是否符合
  if (
    ['video/mp4', 'video/ogg', 'video/flv', 'video/avi', 'video/wmv', 'video/rmvb'].indexOf(
      file.type
    ) === -1
  ) {
    message.error('请上传正确的视频格式')
    return false
  }
  // 判断视频大小是否超过100M
  else if (isLitmit > 100) {
    message.error('视频大小不能超过100M')
    return
  } else {
    message.success('视频正在上传')
  }
}

// 视频上传错误
const excelUploadError: UploadProps['onError'] = (): void => {
  message.error('导入数据失败，请您重新上传！')
}

// // 文件移除
const handleFileRemove = async (file: UploadRawFile) => {
  const findex = fileList.value.map((f) => f.name).indexOf(file.name)
  if (findex > -1) {
    fileList.value.splice(findex, 1)
  }
  recordVideo.value = ''
  ElMessage.success('删除成功')
}
// 文件超出个数限制
const handleExceed = () => {
  ElMessage.warning('超出文件个数限制')
}

const handleVideoSuccess = (response: any, UploadFile: UploadFile) => {
  recordVideo.value = response.data
  ElMessage.success('视频上传成功')
}
</script>

<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="700">
    <Form :schema="schema" @register="register">
      <template #videoUrl>
        <div>
          <el-upload
            class="avatar-uploader"
            :action="updateUrl"
            list-type="picture-card"
            v-model:file-list="fileList"
            :limit="1"
            :auto-upload="true"
            :headers="uploadHeaders"
            :show-file-list="true"
            :before-upload="beforeUploadVideo"
            :on-remove="handleFileRemove"
            :on-success="handleVideoSuccess"
            :on-exceed="handleExceed"
            :on-error="excelUploadError"
          >
            <!-- TOOD：视频预览 -->
            <!-- <video v-if="recordVideo" class="h-full" :src="recordVideo"></video> -->
            <el-icon><Plus /></el-icon>
          </el-upload>
        </div>
      </template>
    </Form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
